package com.pocketsweet.ui;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.avos.avoscloud.AVAnalytics;
import com.easemob.chat.EMContactManager;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.pocketsweet.C;
import com.pocketsweet.MLCache;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.HeaderLayout.onRightContainerListener;
import com.pocketsweet.ui.uilib.SideBar;
import com.pocketsweet.ui.uilib.SideBar.OnTouchingLetterChangedListener;
import com.pocketsweet.ui.uilib.adapter.SortAdapter;
import com.pocketsweet.utils.CharacterParser;
import com.pocketsweet.utils.PinyinComparator;
import com.pocketsweet.utils.SortModel;

@ContentView(R.layout.activity_friend)
public class Friend extends BaseActivity {

	private Context mContext;
	private List<JSONObject> contactList;
	private List<String> blackList;
	private ListView sortListView;
	private SideBar sideBar;
	private TextView dialog;
	private SortAdapter adapter;

	private LinearLayout linBankFriends;

	private HeaderLayout rvHeader;
	
	private Friend friendInstance;

	/**
	 * 汉字转换成拼音的类
	 */
	private CharacterParser characterParser;
	private List<SortModel> SourceDateList;

	/**
	 * 根据拼音来排列ListView里面的数据类
	 */
	private PinyinComparator pinyinComparator;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		mContext = this;
		friendInstance=this;
		initHeader();
		initView();
	}
	
	public Friend getFriendInstance(){
		return friendInstance;
	}
	
	private void initHeader() {
		// 导航header
		rvHeader = (HeaderLayout) findViewById(R.id.friendHeader);
		rvHeader.init(HeaderStyle.IMG_TITLE_IMG);
		rvHeader.setMiddleText("恋人");
		rvHeader.setRightContentShow(View.VISIBLE);
		rvHeader.setRightImg(R.drawable.lover_add_icon);
		rvHeader.setRighttContainerClickListener(new onRightContainerListener() {

			@Override
			public void onClick() {
				Intent intent = new Intent(mContext, AddFriend.class);
				mContext.startActivity(intent);
				AVAnalytics.onEvent(Friend.this, "搜索添加恋人");
			}
		});
		rvHeader.setLeftContainerClickListener(new onLeftContainerListener() {

			@Override
			public void onClick() {
				Friend.this.finish();
			}
		});
		//rvHeader.setRightImg(R.drawable.back);
		rvHeader.setLeftContentShow(View.VISIBLE);

	}

	private void initView() {
		// 实例化汉字转拼音类
		characterParser = CharacterParser.getInstance();

		pinyinComparator = new PinyinComparator();

		sideBar = (SideBar) findViewById(R.id.sidrbar);
		dialog = (TextView) findViewById(R.id.dialog);
		linBankFriends = (LinearLayout) findViewById(R.id.linBlankFriends);
		sideBar.setTextView(dialog);

		// 设置右侧触摸监听
		sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				// 该字母首次出现的位置
				if (s.equals("↑")) {
					sortListView.setSelection(0);
				} else {
					int position = adapter.getPositionForSection(s.charAt(0));
					if (position != -1) {
						sortListView.setSelection(position);
					}
				}
			}
		});

		sortListView = (ListView) findViewById(R.id.lvFriendList);
		sortListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// 这里要利用adapter.getItem(position)来获取当前position所对应的对象
				// User user = ((SortModel)
				// adapter.getItem(position)).getUser();
				// String userId = user.getUsername();

				// ToolKits.toast(MLApplication.getContext(),
				// ((SortModel) adapter.getItem(position)).getName());
			}
		});

		// 黑名单列表
		blackList = EMContactManager.getInstance().getBlackListUsernames();
		contactList = new ArrayList<JSONObject>();
		// 获取设置contactlist
		getContactList();
		SourceDateList = filledData(contactList);

		// 根据a-z进行排序源数据
		Collections.sort(SourceDateList, pinyinComparator);
		adapter = new SortAdapter(mContext, SourceDateList);
		sortListView.setAdapter(adapter);
		sortListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				SortModel user = (SortModel) adapter.getItem(position);
				try {
					String selectedUserId = user.getUser()
							.getString("objectId");
					Intent intent = new Intent(mContext, Profile.class);
					intent.putExtra("userId", selectedUserId);
					intent.putExtra("nickname", user.getUser().getString("nickname"));
					mContext.startActivity(intent);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});

	}

	private void getContactList() {
		contactList.clear();
		contactList = MLCache.getAllFriend();
//		Log.e("==contactlist","contact:"+String.valueOf(contactList.size()));
//		Log.e("==fff=","contact:"+contactList.toString());

		if (contactList.size() <= 0) {
			linBankFriends.setVisibility(View.VISIBLE);
			sideBar.setVisibility(View.INVISIBLE);
		} else {
			linBankFriends.setVisibility(View.GONE);
			sideBar.setVisibility(View.VISIBLE);
		}
		SourceDateList = filledData(contactList);
		// 根据a-z进行排序源数据
		Collections.sort(SourceDateList, pinyinComparator);
		adapter = new SortAdapter(mContext, SourceDateList);
		sortListView.setAdapter(adapter);
	}

	private List<SortModel> filledData(List<JSONObject> contactList) {
		List<SortModel> mSortList = new ArrayList<SortModel>();
		try {

			// Log.e("name", contactList.toString());
			for (int i = 0; i < contactList.size(); i++) {
				SortModel sortModel = new SortModel();
//				Log.e("===","contact:"+contactList.get(i).toString());
				sortModel.setName(contactList.get(i).getString("objectId"));

				// 汉字转换成拼音
				String pinyin = characterParser.getSelling(contactList.get(i)
						.getString("nickname"));
				if (pinyin.length() > 0) {
					String sortString = pinyin.substring(0, 1).toUpperCase();

					// 正则表达式，判断首字母是否是英文字母
					if (contactList.get(i).getInt("type") == C.USER_TYPE_RECOMMENDED) {
						sortModel.setSortLetters("☆");
					} else {
						if (sortString.matches("[A-Z]")) {
							sortModel.setSortLetters(sortString.toUpperCase());
						} else {
							sortModel.setSortLetters("#");
						}
					}

					sortModel.setUser(contactList.get(i));
					mSortList.add(sortModel);
				}
			}

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return mSortList;

	}

}
